﻿using log4net;
using Newtonsoft.Json.Linq;
using SQLDataUploadHelper.commons.utils;
using SQLDataUploadHelper.models;
using SQLDataUploadHelper.models.domain;
using System;
using System.Collections.Generic;
using System.Data;

namespace SQLDataUploadHelper.services
{
    /// <summary>
    /// 数据上送
    /// </summary>
    internal class SQLUploadService
    {
        private readonly ILog log = LogManager.GetLogger(App.LogRepository.Name, typeof(SQLUploadService));
        private UploadServerConfigService uploadServerConfigService = new UploadServerConfigService();

        /// <summary>
        /// 上送遍历
        /// </summary>
        /// <returns></returns>
        public void uploadAll(SqlConnectConfig mysqlConnectInfo)
        {
            SQLErgodicService sqlErgodicService = new SQLErgodicService(mysqlConnectInfo);
            //step1 获取所有表
            List<string> tables = sqlErgodicService.getTables();
            List<UploadServerConfig> uploadServerConfigs = uploadServerConfigService.list();

            //step2 遍历表中未上送数据
            foreach (string tableName in tables)
            {
                int pageNum = 1;
                int pageSize = 100;
                DataTable? dataTable;
                do
                {
                    dataTable = sqlErgodicService.selectData(tableName, pageNum++);
                    if (dataTable == null)
                    {
                        log.Warn("获取数据结果为空");
                        break;
                    }
                    //List<string> columns = sqlErgodicService.getCloumnsName(dataTable);
                    List<JObject> jsonTableData = dataTable2JObject(dataTable);
                    if (jsonTableData.Count == 0)
                    {
                        break;
                    }

                    //step3 上送数据
                    UploadRequest uploadRequest = new UploadRequest();
                    uploadRequest.TableName = tableName;
                    uploadRequest.Data = jsonTableData;
                    foreach (UploadServerConfig uploadServerConfig in uploadServerConfigs)
                    {
                        UploadResponse uploadResponse;
                        if (upload(uploadServerConfig.Url, uploadRequest, out uploadResponse))
                        {
                            //上送成功
                            if (uploadResponse.ReturnValue != null)
                            {
                                sqlErgodicService.updateUploadStatus(uploadResponse.ReturnValue.TableName, uploadResponse.ReturnValue.ids);
                            }
                        }
                    }
                }
                while (dataTable.Columns.Count == pageSize);
            }
        }

        /// <summary>
        /// 查询结果转Json
        /// </summary>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        private List<JObject> dataTable2JObject(DataTable dataTable)
        {
            List<JObject> datas = new List<JObject>();
            foreach (DataRow dataRow in dataTable.Rows)
            {
                JObject data = new JObject();
                foreach (DataColumn dataColumn in dataTable.Columns)
                {
                    object columnValue = dataRow[dataColumn.ColumnName];
                    if (columnValue == null)
                    {
                        continue;
                    }
                    if (dataColumn.DataType.Equals(Type.GetType("System.DateTime")))
                    {
                        data[dataColumn.ColumnName] = Convert.ToDateTime(columnValue).ToString("yyyy-MM-dd HH:mm:ss").Trim();
                    }
                    else if (dataColumn.DataType.Equals(Type.GetType("System.Int32")))
                    {
                        data[dataColumn.ColumnName] = Convert.ToInt32(columnValue);
                    }
                    else if (dataColumn.DataType.Equals(Type.GetType("System.UInt32")))
                    {
                        data[dataColumn.ColumnName] = Convert.ToUInt32(columnValue);
                    }
                    else
                    {
                        try
                        {
                            data[dataColumn.ColumnName] = columnValue.ToString();
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex.ToString());
                            data[dataColumn.ColumnName] = "";
                        }

                    }
                }
                datas.Add(data);
            }
            return datas;
        }

        /// <summary>
        /// 上送
        /// </summary>
        /// <returns>上送结果</returns>
        private bool upload(string url, UploadRequest uploadRequest, out UploadResponse uploadResponse)
        {
            string request = uploadRequest.toJson();
            log.Info("请求参数=" + request);
            string response = "";
            bool result = HttpUtils.HttpJsonPost(url, request, out response);
            log.Info("响应参数=" + response);
            if (result)
            {
                uploadResponse = UploadResponse.parse(response);
            }
            else
            {
                uploadResponse = new UploadResponse();
            }
            return result;
        }
    }
}
